package com.etcn.common.payment.wxpay.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

import com.etcn.common.payment.wxpay.constants.WxPayConstants;
import com.etcn.common.utils.secret.MD5Util;

/**
 * 微信签名工具类
 * @author guozc
 * @date 2016-02-18
 */
public class WxPaySignature {

	/**
	 * 签名
	 * @param map
	 * @return
	 */
    public static String sign(Map<String,Object> map){
    	map.remove("sign");
        ArrayList<String> list = new ArrayList<String>();
        for(Map.Entry<String,Object> entry:map.entrySet()){
            if(entry.getValue()!=""){
                list.add(entry.getKey() + "=" + entry.getValue() + "&");
            }
        }
        int size = list.size();
        String [] arrayToSort = list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < size; i ++) {
            sb.append(arrayToSort[i]);
        }
        String result = sb.toString();
        result += "key=" + WxPayConstants.KEY;
        result = MD5Util.Md5(result).toUpperCase();
        return result;
    }
    
}
